from flask import Flask,jsonify,request,Blueprint,session
from common.res import (getRes,getErrorRes,getSuccessRes,getDataRes)
from common.sqlInjectionSecurity import sqlEscape,sqlEscapeField
from DAL.loginDAL import loginDAL

login = Blueprint('login',__name__)

@login.route("/login/logit",methods=['POST'])
def logit(): 
    param = {
        'account': request.form.get('account') and sqlEscape(request.form.get('account')) or None,
        'password': request.form.get('password') and sqlEscape(request.form.get('password')) or None
          }
    dal = loginDAL()
    data = dal.login(**param)
    if data:
        session['token'] = data['token']
        session['account'] = data['account']
        res = getSuccessRes(data=data)
    else:
        res = getErrorRes("你输入的用户和密码有误！")
    return jsonify(res)

@login.route("/login/getuserinfo",methods=['POST'])
def getUserInfo():
    token = session.get('token')
    if not token:
        res = getErrorRes("你的token已经过期！")
        return jsonify(res)
    dal = loginDAL()
    data = dal.getUserInfo(token)
    res = getSuccessRes(data=data)
    return jsonify(res)

@login.route("/login/autologin",methods=['POST'])
def autologin():
    token = session.get('token')
    if not token:
        res = getErrorRes("你的token已经过期！")
        return jsonify(res)
    dal = loginDAL()
    data = dal.loginByToken(token)
    res = getSuccessRes(data=data)
    return jsonify(res)
@login.route("/login/logItOut",methods=['POST'])
def logout():
    token = session.get('token')
    # print('logout',token)
    if not token:
        res = getErrorRes("你的token已经过期！")
        return jsonify(res)
    dal = loginDAL()
    data = dal.loginOut(token)
    res = getSuccessRes(msg="成功退出",data=data) if data>0 else getErrorRes(msg="退出失败",data=data)
    return jsonify(res)

